""" 
需求:
人物中心显示, 四周变为黑色

"""

import numpy as np
import cv2 as cv
from dataclasses import dataclass


# 保留的区域 像素坐标
@dataclass
class roi_pos:
    x1: int
    y1: int
    x2: int
    y2: int


# numpy 矩形数组操作 改为 起始坐标和结束坐标
def roi_set_by_pos(nums, x1, y1, x2, y2, value):
    nums[y1:y2, x1:x2] = value


# 方法1: 通过绘制多个矩形区域
def image_masking_cal(img, reten_pos):
    y, x = img.shape[:2]
    # 保留起始坐标
    x1, y1 = reten_pos.x1, reten_pos.y1
    # 保留结束坐标
    x2, y2 = reten_pos.x2, reten_pos.y2
    print(f"{x}:{y}, pos: {x1}:{y1}, {x2}:{y2}")
    new_img = img.copy()

    # 划分9宫格, 中心区域保留, 其他区域变为黑色
    # _|_|_
    # _|_|_
    #  | |

    # 123分区
    roi_set_by_pos(new_img, 0, 0, x, y1, value=(0, 0, 0))
    # # 4分区
    roi_set_by_pos(new_img, 0, y1, x1, y2, value=(0, 0, 0))
    # # 6分区
    roi_set_by_pos(new_img, x2, y1, x, y2, value=(0, 0, 0))
    # # 789分区
    roi_set_by_pos(new_img, 0, y2, x, y, value=(0, 0, 0))

    return new_img


# 方法2: 通过与运算
def image_masking_bitwise_and(img, reten_pos):
    y, x = img.shape[:2]
    mask_img = np.zeros((y, x, 3), dtype=np.uint8)

    # 绘制保护区域
    x1 = reten_pos.x1
    y1 = reten_pos.y1
    x2 = reten_pos.x2
    y2 = reten_pos.y2
    cv.rectangle(mask_img, (x1, y1), (x2, y2), (255, 255, 255), -1)
    cv.imshow("debug_mask_img", mask_img)

    # 与运算
    new_img = cv.bitwise_and(img, mask_img)

    return new_img


def test_person_masking():
    # 原始图像
    person_picture = "../../res/117.jpg"
    img = cv.imread(person_picture)
    img = cv.resize(img, None, fx=0.5, fy=0.5)
    cv.imshow("origin_img", img)
    # 人物头像坐标
    person_pos = roi_pos(200, 253, 518, 611)
    cal_mask_img = image_masking_cal(img, person_pos)
    and_mask_img = image_masking_bitwise_and(img, person_pos)
    cv.imshow("cal_mask_img", cal_mask_img)
    cv.imshow("and_mask_img", and_mask_img)


def test_tiny_masking():
    # 使用 np.full 创建一个4x4的三通道数组，每个通道分别设置为50, 100, 150
    img = np.full((4, 4, 3), [50, 100, 150], dtype=np.uint8)
    reten_pos = roi_pos(1, 1, 2, 2)
    mask_img = image_masking_cal(img, reten_pos)
    cv.imshow("mask_img", mask_img)


if __name__ == "__main__":
    test_person_masking()
    # test_tiny_masking()
    cv.waitKey(0)
    cv.destroyAllWindows()
